package com.speedchina.common.rsa.resolver;

import com.alibaba.fastjson.JSON;
import com.speedchina.common.rsa.service.RSAService;
import com.speedchina.common.rsa.util.RSAUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLDecoder;

/**
 * @author ：wangxiaodong
 * @description：TODO
 * @date ：2021/4/18 10:47
 */
@Data
@Slf4j
public class RequestBodyRSAArgumentResolver implements HandlerMethodArgumentResolver {

    private RSAService rsaService;
    /**
     * 解析Content-Type为application/json的默认解析器是RequestResponseBodyMethodProcessor
     */
    private RequestResponseBodyMethodProcessor requestResponseBodyMethodProcessor;
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(RequestBodyRSA.class);
    }


    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        //parameter.getGenericParameterType() 返回参数的完整类型（带泛型）
        final Type type = parameter.getGenericParameterType();
        String publicKey = request.getHeader("publicKey");
        String privateKey = rsaService.getPrivateKey(publicKey);
        rsaService.removePublicKeyPrivateKey(publicKey);
        String receiveJson = receivePost(request);
        log.debug(publicKey);
        log.debug(receiveJson);
        String json = RSAUtils.decryptByPrivateKey(privateKey,receiveJson);
        log.debug(json);
        final Object o = JSON.parseObject(json, type);
//        return requestResponseBodyMethodProcessor.resolveArgument(parameter,
//                mavContainer, webRequest, binderFactory);
        return o;
    }
    public static String receivePost(HttpServletRequest request) throws IOException, UnsupportedEncodingException {

        // 读取请求内容
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while((line = br.readLine())!=null){
            sb.append(line);
        }

        // 将字符解码
        String reqBody = sb.toString();
        return URLDecoder.decode(reqBody, "utf-8");
    }
}
